<!-- 
      cart.html
     租赁车， id= cart
      
      Created by tang on 2017-03-15.
      Copyright 2017 tang. All rights reserved.
 -->
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title></title>
    <script src="../js/mui.js"></script>
    <link href="../css/mui.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="../css/cart.css" />
</head>
<body class="gray">
	<div class="mui-content mui-fullscreen loading" id="vueMain">
		<div class="cart-tab">
			<div class="mui-row">
				<div class="mui-col-xs-4 mui-col-sm-4 mui-active" _href="cartView"><span>租赁车</span></div>
				<div class="mui-col-xs-4 mui-col-sm-4" _href="collectView"><span>收藏</span></div>
				<div class="mui-col-xs-4 mui-col-sm-4" _href="logView"><span>历史记录</span></div>
			</div>
		</div>
		<div class="mui-slider-group " >
			<div id="cartView" class="mui-slider-item mui-control-content mui-active">
				<div id="scroll1" class="mui-scroll-wrapper">
					<div class="mui-scroll cartbox" style="padding-bottom: 60px;;">
						<!--<div id="cartStatus" >您的租赁车有新动态哦! <span id="getCartData">马上加载</span></div>-->
						<div v-if="cart.list.length<1">
							<p style="text-align: center;color: #666;padding:70px 0 ;">
								哎哟！您的租赁车是空的哦！ 
							</p>
						</div>
						<template v-else v-for="(item,index) in cart.list">
							<ul class="mui-table-view">
								<li class="mui-table-view-cell checkbox-list ">
									<span class="mui-pull-right link" _id="confirmOrder" _href="confirmOrder.html" _title="订单确认" :_extras="'order_no='+item.order_no + '&otype=2'">查看订单</span>
									<div class="mui-input-row mui-checkbox listCheckbox mui-left" :data-idx="index">
										<label style="padding-left: 35px;">{{item.order_no}}</label>
										<input name="v1" :value="index" type="checkbox"  />
									</div>
								</li>
								<li class="mui-table-view-cell product-list">
									<div class="mui-slider-right mui-disabled">
										<a class="mui-btn mui-btn-red removeCart" :data-idx="index">删除</a>
									</div>
									<div class="mui-slider-handle">
										<!--<div class="mui-input-row mui-checkbox itemCheckbox mui-left mui-pull-left" >
											<label>&nbsp;</label>
											<input name="v1" :value="item.index" type="checkbox"   />
										</div>-->
										<img class="mui-media-object mui-pull-left" :data-load="item.img" src="../icon/mask-small.png" />
			  				            <div class="mui-media-body link" _id="detail" _href="detail.html" :_extras="'pid='+item.goods_id" >
			  				               <div class="name">{{item.name}}</div>
			  				               <p v-if="item.start_time==item.end_time">{{item.start_time}} 共{{item.goods_nums}}天</p>
			  				               <p v-else>{{item.start_time}}-{{item.end_time}}  共{{item.goods_nums}}天</p>
			  				               <p v-if="item.stro">已选：{{item.stro}}</p>
			  				               <p>数量: {{item.amount}}</p>
			  				               <div class="price">订金：<b class="text-red">¥ {{item.pay_fee}}</b></div>
			  				            </div>
									</div>
								</li>
							</ul>
						</template>
						<div class=" cainilike" v-if="cart.like.length!=0">
					   	 	<div class="ts">猜你喜欢</div>
					   	 	<div class="mui-row">
					   	 		<template v-for="item in cart.like">
									<div class="itemslink mui-col-xs-6 mui-col-sm-6 link" _id="detail" _href="detail.html" :_extras="'pid='+item.id">
					   	 				<img :src="item.img" alt="" />
						    				<p class="name">{{item.name}}</p>
						    				<p class="price" v-if="item.price!=0.00">¥{{item.price}}</p>
						    				<p class="price" v-else>询价</p>
					   	 			</div>		   	 			
					   	 		</template>
					   	 	</div>
					    </div>
					</div>
				</div>
			</div>
			<div id="collectView" class="mui-slider-item mui-control-content">
				<div id="scroll2" class="mui-scroll-wrapper">
					<div class="mui-scroll collectView">
						<div class="mui-loading">
							<div class="mui-spinner">
							</div>
						</div>
						<div v-if="collect.msg.length == 0">
							<p style="text-align: center; padding: 50px 0;">您没有收藏</p>
						</div>
						<ul v-else class="mui-table-view">
							<template v-for="(item,index) in collect.msg">
								 <li class="mui-table-view-cell mui-media">
							        <div class="mui-slider-handle">
							        		<div class="mui-input-row mui-checkbox mui-left mui-pull-left" :data-idx="index">
											<label>&nbsp;</label>
											<input name="v1" :value="index" type="checkbox" v-bind:checked="item.isActive!=0" />
										</div>
							            <img class="mui-media-object mui-pull-left link" :data-load="item.img" src="../icon/mask-small.png" _id="detail" _href="detail.html" :_extras="'pid='+item.goods_id">
							            <div class="mui-media-body">
							                {{item.name}}
							                <div class="money"  v-if="item.price!='0.00'">¥ {{item.price}}</div>
							                 <div class="money" v-else>询价</div>
							                <div class="control" style="float: right;">
							                		<button type="button" class="mui-btn bexta-btn btn-default mui-btn-outlined likeness" :data-idx="index">看相似</button>
							                </div>
							            </div>
							        </div>
							    </li>
							</template>
						</ul>
						<div class="cainilike" v-if="collect.like.length!=0">
					   	 	<div class="ts">猜你喜欢</div>
					   	 	<div class="mui-row">
					   	 		<template v-for="item in collect.like">
									<div class="itemslink mui-col-xs-6 mui-col-sm-6 link" _id="detail" _href="detail.html" :_extras="'pid='+item.id">
					   	 				<img :src="item.img" alt="" />
						    				<p class="name">{{item.name}}</p>
						    				<p class="price" v-if="item.price!=0.00">¥{{item.price}}</p>
						    				<p class="price" v-else>询价</p>
					   	 			</div>		   	 			
					   	 		</template>
					   	 	</div>
					    </div>
					</div>
				</div>
			</div>
			<div id="logView" class="mui-slider-item mui-control-content">
				<div id="scroll3" class="mui-scroll-wrapper">
					<div class="mui-scroll">
						<div v-if="history.length==0">
							<p style="padding:50px 0;text-align: center;">您还没有浏览过呢!</p>
						</div>
						<ul v-else class="mui-table-view">
							<template v-for="(item, index) in history">
								 <li class="mui-table-view-cell mui-media link" _id="detail" _href="detail.html" :_extras="'pid='+item.id">
								    	<div class="mui-slider-right mui-disabled">
										<a class="mui-btn mui-btn-red rmHostry" :data-idx="index">删除</a>
									</div> 
							        <div class="mui-slider-handle">
							            <img class="mui-media-object mui-pull-left " :data-load="item.photo" src="../icon/mask-small.png" >
							            <div class="mui-media-body">
							                {{item.name}}
							                <div class="money" v-if="item.price!='0.00'">¥ {{item.price}}</div>
							                <div class="money" v-else>询价</div>
							                <div class="control">
							                </div>
							            </div>
							        </div>
							    </li>
							</template>
						</ul>
					</div>
				</div>
			</div>
		</div>
	</div>

<div class="cart-count mui-clearfix" id="cart-count">
	<div class="mui-pull-right joinOrder"  >
		结算(<b id="cartNum">0</b>)
	</div>
	<div class="count" style="text-align: left; padding-left: 10px;">
		<div class="mui-input-row mui-checkbox allCheckbox mui-left mui-pull-left">
			<label>全选</label>
			<input name="v1" value="1" type="checkbox" >
		</div>
		<span>合计：¥ <span id="cartCount">0</span></span>
	</div>
</div>

<script src="../js/vue.min.js"></script>
<script src="../js/mui.pullToRefresh.js"></script>
<script src="../js/mui.pullToRefresh.material.js"></script>
<script src="../js/bexta.js"></script>
<script type="text/javascript">
	var apps, isReady = false, colup;
	mui.init();
	window.addEventListener('readyVue', function(){
		if( !isReady ){
			getCartData(function(res){
				isReady = true;
				initVue(res);
			});
		}
	});
	mui.plusReady(function () {
	    plus.webview.currentWebview().addEventListener('show', function(){
	    		mui.each(document.querySelectorAll('.listCheckbox input'), function(){
	    			this.checked = false;
	    		});
	    		countCart();
		    	setTimeout(function(){
		    		if(isReady){
		    			getCartData(function(res){
						apps.cart = res;
					});
		    		}
		    	},100)
		});
	})
	window.addEventListener('reloadCartData', function(){
		getCartData(function(res){
			apps.cart = res;
			mui('#scroll1').scroll().scrollTo(0,0,100);
		});
	});
	function initVue(res) {
		apps = new Vue({
			el:'#vueMain',
			data:{
				orders:[],
				cart:res || {},   //租赁车列表
				collect:{
					first:0,
					last:10,
					msg:[],
					like:[]
				}, //收藏列表
				history:[],  //历史记录
				joinCart:[]   //已选好的租赁品
			},
			mounted:function(){
				initMounted();
				initEvent();
				bexta.imageLoad('[data-load]');
				document.querySelector('.loading').classList.add('loadRun');
			},
			updated:function(){
				bexta.imageLoad('[data-load]');
			}
		});
	}
	function countCart() {
		//计算租赁车的数量和价钱
		var num = 0, count = 0;
		var list = document.querySelectorAll('.listCheckbox input');
		console.log( list.length );
		mui.each(list, function(){
				if( this.checked ){
					var idx = this.value;
					var pay_fee = parseFloat(apps.cart.list[idx].pay_fee);
					num++;
					count += pay_fee;
				}
			

		});
		if( num < list.length ){
			document.querySelector('.allCheckbox input').checked = false;
		}else if( num == list.length ){
			document.querySelector('.allCheckbox input').checked = true;
		}
		document.getElementById('cartNum').innerHTML = num;
		document.getElementById('cartCount').innerHTML = count;
	}
	function getCartData(cfun) {
		//重新获取购物车的数据；
		var user = bexta.getStorage(USER);
			bexta.ajax(api.cartlist, function(res){
				cfun(res);
			},{data:{uid:user.uid}});
	}
	function getCollectData(cfun, first,last){
		//获取收藏商品
		bexta.ajax(api.collect_list, function(res){
			cfun(res);
//			bexta.imageLoad('[data-load]');
		}, {data:{firstrow:(first==0?0: apps.collect.first ), listrow:last || apps.collect.last, uid:bexta.getStorage(USER).uid}})
	}
	function initEvent() {
		//重新获取租赁车数据
		mui('body').on('tap', '#getCartData', function(){
			document.getElementById('cartStatus').style.display = 'none';
			getCartData(function(res){
				apps.cart = res;
			});
		})
		//-->
		//刷新租赁车
		mui('.mui-slider-group').on('tap', '#refreshCart', function(){
			getCartData(function(res){
				if( res.list.length > 0 ){
					apps.cart = res;
				}else{
					mui.toast("哟呵！租赁车还是空的呢");
				}
				
			});
		});
		//cart删除商品
		mui('.mui-slider-group').on('tap', '.removeCart', function() {
			var idx = this.getAttribute('data-idx');
			var order = apps.cart.list[idx].order_no;
			var li = this.parentNode.parentNode;
			bexta.ajax(api.del_order, function(res, msg){
				mui.toast(msg);
				if( !res ){
					mui.swipeoutClose(li);
					apps.cart.list.splice(idx,1);
					setTimeout(function() {
						countCart();
					},500);
				}
			},{data:{uid:bexta.getStorage(USER).uid, type:1, order_no:order}});
		});
		//->cart删除
		//cart选择
		mui('.mui-slider-group').on('tap', '.itemCheckbox', function() {
		});
		mui('.mui-slider-group').on('tap', '.listCheckbox', function(){
			//商家条目全选
			mui.later(function(){
				countCart();
			},10)
			
		});
		mui('#cart-count').on('tap', '.allCheckbox', function() {
			var ch = this.querySelector('input');
			mui.each(document.querySelectorAll('.listCheckbox input'), function(){
					this.checked = !ch.checked;
				});
			mui.later(function(){
				countCart();
			},10);
//			
		});
		//->cart选择
		mui('#collectView').on('tap', '.mui-checkbox', function(){
			var idx = this.getAttribute('data-idx');
			var k = apps.collect.msg[idx].isActive;
			apps.collect.msg[idx].isActive = k == 0?1:0;
//			bexta.jsonToString( apps.collect.msg[idx] )
		});
		mui('#collectView').on('tap', '.likeness', function(){
			var idx = this.getAttribute('data-idx');
			var list = apps.collect.msg[idx];
			if( list.commend_id == 1 || list.commend_id == 5 || list.commend_id == 6 || list.commend_id == 7 || list.commend_id == 8 ){
				//
				bexta.openWithTitle({
					id:"newList2",
					url:'newList2.html',
					extras:{
						type:list.commend_id,
						sid:list.sid,
						look:'normal'
					}
				}, {
					title:{
						text:"看相似"
					}
				});
			}else{
				bexta.openWithTitle({
					id:"newList",
					url:'newList.html',
					extras:{
						type:list.commend_id,
						sid:list.sid,
						look:'normal'
					}
				}, {
					title:{
						text:"看相似"
					}
				});
			}
			
			
//				gid = this.getAttribute('data-gid');
//			var list = apps.collect.msg[idx];
//			if( list.goods_id == gid ){
//				var sendData = {
//					commend_id:list.commend_id,
//					class_id:list.class_id,
//					goods_id:list.goods_id,
//					model_id:list.model_id
//				};
//			}else{
//				var d = null;
//				mui.each(apps.collect.msg, function(){
//					if( this.goods_id == gid ){
//						d = this;
//					}
//				});
//				var sendData = {
//					commend_id:d.commend_id,
//					class_id:d.class_id,
//					goods_id:d.goods_id,
//					model_id:list.model_id
//				};
//			}
//			bexta.openWithTitle({
//				id:'list',
//				url:'list.html',
//				extras:{
//					sendData :sendData
//				}
//			},{},true);
		});
		//提交订单
		mui('#cart-count').on('tap', '.joinOrder', function(){
			var order = [];
			mui.each(document.querySelectorAll('.listCheckbox input'), function(){
				if( this.checked ){
					var idx = this.value;
					order.push(apps.cart.list[idx].order_no);
				}
			});
			if( order.length < 1 ){
				mui.toast("请勾选需要结算的订单");
				return ;
			}
			bexta.ajax(api.update_order, function(res){
				bexta.openWithTitle({
					id:'pay',
					url:'pay.html',
					extras:{
						data:res
					}
				}, {
					title:{
						text:"订单支付"
					}
				});
			},{data:{uid:bexta.getStorage(USER).uid, order_no:order.join(','),is_pay:1}});
		});
	}
	function countJoinOrder(){
		//订算要提交的订单！！！每一次按都会计算一次
		var goods = [];
		mui.each(apps.cart.list, function(){
			for( var index = 0; index < this.list.length; index++ ){
				if( this.list[index].isActive == 1 ){
					goods.push(this.list[index].goods_id + '_' + this.list[index].product_id);
				}
			}
		});
		return goods;
	}
	
	function initMounted(){
		mui('.mui-scroll-wrapper').scroll({
			indicators: true  //是否显示滚动条
		});
		//tab 切换
		mui('.cart-tab').on('tap', '.mui-col-sm-4', function() {
			var tid = this.getAttribute('_href');
			mui('.cart-tab .mui-active')[0].classList.remove('mui-active');
			this.classList.add('mui-active');
			mui('.mui-slider-item').each(function(){
				if( this.classList.contains('mui-active') && this.id != tid ){
					this.classList.remove('mui-active');
				}else if( this.id == tid ){
					this.classList.add('mui-active');
					if( this.id == 'logView' ){
						var hostry = bexta.getStorage(HOSTRY);
						apps.history = hostry || [];
					}else{
						if( !this.classList.contains('isActive') ){
							//第一次显示
							if( this.id == 'collectView' ){
								//收藏
								this.classList.add('isActive');
								getCollectData(function(res){
									document.querySelector('#collectView .mui-loading').style.display = 'none';
									apps.collect.msg = res.list;
									apps.collect.like = res.like;
									apps.collect.first = res.list.length;
								});
							}
						}
					}
				}
			});
			
			//控制下面的结算条
			var cartCount = document.querySelector('#cart-count');
			if( tid == 'cartView' ){
				cartCount.style.display = 'block';
			}else{
				cartCount.style.display = 'none';
			}
			
			//控制头部的编辑按钮， 只有收藏显示
			var pView = bexta.getWebview().opener();
			if( tid === 'collectView' ){
				mui.fire(pView, 'toggleHeadEvent', {
					type:'block'
				});
			}else{
				mui.fire(pView, 'toggleHeadEvent', {
					type:'none'
				});
			}
		});
		//历史记录 删除
			mui('#logView').on('tap', '.rmHostry', function(){
				var idx = this.getAttribute('data-idx');
				apps.history.splice(idx, 1);
				bexta.setStorage(HOSTRY, apps.history);
				mui.swipeoutClose(this.parentNode.parentNode);
			});
		
		mui.each(document.querySelectorAll('.mui-slider-group .mui-scroll'), function(index, pullRefreshEl) {
			if( pullRefreshEl.classList.contains('cartbox') ){
				return ;
			}
			if( pullRefreshEl.classList.contains('collectView') ){
				colup = pullRefreshEl;
				mui(pullRefreshEl).pullToRefresh({
					down: {
						callback: function() {
							var self = this;
		//						colup = this;
							if(  pullRefreshEl.classList.contains('collectView') ){
								getCollectData(function(res){
									apps.collect.msg = res.list;
									self.endPullDownToRefresh();
								}, 0, apps.collect.last);
							}
						}
					},
					up: {
						show:false,
						callback: function() {
							var self = this;
		//						colup = this;
							if(  pullRefreshEl.classList.contains('collectView') ){
								getCollectData(function(res){
									if( res.list.length == 0 || res.list.length < apps.collect.last ){
										self.endPullUpToRefresh(true);
									}else{
										self.endPullUpToRefresh(false);
									}
									if( res.list.length != 0 ){
										mui.each(res.list, function(){
											apps.collect.msg.push(this);
										});
									}
								});
							}
						}
					}
				});
			}
		});
		
	}
	 //由父面触发的删除事件
	 window.addEventListener('toggleEdit', function(e) {
	 	var checkbox = document.querySelectorAll('#collectView .mui-checkbox');
	 	if( e.detail.text == '编辑' ){
	 		mui.each(checkbox, function(){
	 			this.style.display = 'block';
	 		});
	 	}else if( e.detail.text == '删除' ){
	 		mui.each(checkbox, function(){
	 			this.style.display = 'none';
	 		});
	 		var delArr = [],idxs = [], chen = [] ;
	 		mui.each(apps.collect.msg, function(index,item){
	 			if( item.isActive == 1 ){
	 				delArr.push(item.goods_id);
	 				idxs.push( index );
	 			}else{
	 				chen.push(item);
	 				item.isActive = 0;
	 			}
	 		});
	 		if( delArr.length > 0 ){
	 			bexta.ajax(api.del_collect, function(res, msg){
	 				mui.toast(msg);
	 				apps.collect.msg = chen;
	 				apps.collect.first = chen.length;
	 				mui(colup).pullToRefresh().refresh(true);
	 				mui.scrollTo(0,20)
	 				
	 				mui.each(apps.collect.msg, function(){
	 					this.isActive = 0;
	 				});
	 			}, {data:{uid:bexta.getStorage(USER).uid, goods_id:delArr.join('_')}});
	 		}
	 	}
	 });
	 
</script>
</body>
</html>
